// pages/personal_info/personal_info.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },
    /**
     * 修改头像
     */
    onChangeAvatar() {
        wx.showActionSheet({
          itemList: ['拍照', '从手机相册选择'],
          itemColor: '#3D3D3D'
        }).then(res => {
            // console.log('change avatar success ==>', res);
            if(res.tapIndex === 0) {
                // 点击拍照
                console.log('拍照');
                this.getMedia('camera');
            }else if(res.tapIndex === 1) {
                // 点击从手机相册选择
                console.log('www');
                this.getMedia('album');
            }
        }, err => {
            // 点击取消
            console.log('change avatar error ==>', err);
        });
    },
    /**
     * 修改昵称
     */
    onChangeNick() {
        wx.navigateTo({
          url: '/pages/info_edit/info_edit?type=nick&name=' + this.data.userInfo.nickName,
        });
    },
    /**
     * 修改性别
     */
    onChangeSex() {
        wx.navigateTo({
          url: '/pages/info_edit/info_edit?type=sex&sex=' + this.data.userInfo.gender,
        });
    },
    /**
     * 选择图片
     * @param {String} type 'album'或'camera'
     */
    getMedia(type) {
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: [type],
            camera: 'front'
        }).then(res => {
            // console.log('choose media success ==>', res);
            let imgUrl = res.tempFiles[0].tempFilePath;
            let suffix = this.getImageSuffix(imgUrl);
            console.log('img ==>', imgUrl);
            return wx.cloud.uploadFile({
               cloudPath: 'user_avatar/' + this.getRandomName() + '.' + suffix,
               filePath: imgUrl
            });
        }, err => {
            console.log('choose mdeia error ==>', err);
        }).then(res => {
            // console.log('cloud uploadFile success ==>', res);
            let fileID = res.fileID;
            // console.log('fileID ==>', fileID);
            return [wx.cloud.callFunction({
                name: 'databaseApi',
                data: {
                    type: 'updateUserInfo',
                    reqData: {
                        type: 'avatarUrl',
                        value: fileID
                    }
                }
            }), fileID];
        }, err => {
            console.log('cloud uploadFile error ==>', err);
        }).then(res => {
            // console.log('update avatar success ==>', res);
            // 更新TIM的数据
            wx.$TUIKit.updateMyProfile({
                avatar: res[1]
            });
            // 修改页面数据
            this.setData({
                ['userInfo.avatarUrl']: res[1]
            });
            this.$showMsg('修改成功', 'success');
            // 存储
            app.globalData.userInfo = this.data.userInfo;
            wx.setStorageSync('userInfo', this.data.userInfo);
        }, err => {
            console.log('update avatar error ==>', err);
            this.$showMsg('修改失败', 'fail');
        });
    },
    /**
     * 退出登录
     */
    onLogout() {
        // 清除数据
        // 将本地存储清除
        wx.removeStorageSync('userInfo');
        wx.removeStorageSync('isTimUpdate');
        wx.removeStorageSync('userID');
        wx.removeStorageSync('userSig');
        // 将全局数据还原
        app.globalData.isTimLogin = false;
        app.globalData.isTimUpdate = false;
        app.globalData.isNotLogin = true;
        app.globalData.userInfo = {};
        app.globalData.userID = '';
        app.globalData.userSig = '';
        // 退出 TIM 登录
        wx.$TUIKit.logout()
            .then(res => {
                // console.log('logout TIM success ==>', res);
            }, err => {
                console.log('logout error ==>', err);
            });
        // 返回我的页
        wx.reLaunch({
            url: '/pages/my/my',
        });
    },
    /**
     * 获取登录用户信息
     */
    getUserInfo() {
        let userInfo = wx.getStorageSync('userInfo');
        if(userInfo) {
            this.setData({
                userInfo: userInfo,
            });
        }
        // console.log('userInfo ==>', this.data.userInfo);
    },
    /**
     * 获取一个随机的文件名
     */
    getRandomName() {
        let name = '';
        let origin = 'acegikmoqs';
        let dateStr = new Date().getTime().toString();
        let rStr = ('00' + Math.floor(Math.random() * 1000)).slice(-3);
        let nameStr = rStr + dateStr;
        for(let i = 0; i < nameStr.length; i++) {
            name += origin[nameStr[i]];
        }
        return name;
    },
    /**
     * 获取图片后缀
     * @param {String} imgUrl 
     */
    getImageSuffix(imgUrl) {
        let list = imgUrl.split('.');
        return list[list.length - 1];
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getUserInfo();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    /**
     * 显示提示
     * @param {*} msg 
     * @param {*} type 
     */
    $showMsg(msg, type = 'none') {
        wx.showToast({
            title: msg,
            icon: type
        });
    }
})